#include "singleplayer.h"
#include "ui_singleplayer.h"
#include  <QPushButton>
#include <QMessageBox>
#include <QDebug>

SinglePlayer::SinglePlayer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SinglePlayer)
{
    ui->setupUi(this);
    this->setWindowTitle("五子棋-单机");
    this->setFixedSize(900,600);
    ui->btn_restart->move(220, 500);
    ui->btn_back->move(530, 500);


    // 创建棋盘
    chessBoard = new ChessBoard(this);
    chessBoard->move(220, 20);

    // 按钮功能设定
    connect(ui->btn_back, &QPushButton::clicked, this, &SinglePlayer::back);
    connect(ui->btn_restart, &QPushButton::clicked, this, [=](){
        chessBoard->reset_board();
    });

    // 落子 信号绑定
    connect(chessBoard, &ChessBoard::pos_press, this, &SinglePlayer::set_chess);

    // 设定开始游戏
    chessBoard->setGame_start(true);
}

SinglePlayer::~SinglePlayer()
{
    delete ui;
}

// 设置窗口背景
void SinglePlayer::paintEvent(QPaintEvent *ev)
{
    QPainter *painter = new QPainter(this);
    // 设置绘画内容
    QPixmap pix;
    pix.load(":/res/background.jpg");
    pix.scaled(this->width(), this->height());

    // 画家在指定位置 将预设内容画出来
    painter->drawPixmap(0, 0, this->width(), this->height(), pix);
    delete painter;
}

// 槽函数 在收到棋盘点击后发出的信号时在相应位置落子
void SinglePlayer::set_chess(int pos[])
{
    // 玩家落子
    bool flag = chessBoard->set_chess(pos[0], pos[1], WHITE);
    if(!flag)
    {
        QMessageBox::information(this, "信息", "恭喜你 赢啦!");
    }
    else
    {
        // AI落子
        int row, col;
        chessBoard->findPos(row, col, BLACK);
        flag = chessBoard->set_chess(row, col, BLACK);
        if(!flag)
        {
            QMessageBox::information(this, "信息", "很遗憾 你输了");
        }
    }
}
